package org.springblade.modules.task;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.huikecloud.service.AsyncService;
import org.springblade.modules.task.entity.BladeJob;

import java.lang.reflect.Method;

public class QuartzJobFactory implements Job {
    public static AsyncService asyncService = SpringUtil.getBean(AsyncService.class);

    public void execute(JobExecutionContext context) {
        BladeJob bladeJob = (BladeJob) context.getMergedJobDataMap().get("BladeJob");
        System.out.println("执行任务" + bladeJob.toString());
//      通过反射调用scheduleJob中定义的方法
        Object object = null;
        Class clazz;
        boolean flag=true;
        try {
            if (1 == bladeJob.getJobType()) {
                clazz = Class.forName(bladeJob.getJobName());
                object = clazz.newInstance();
            } else if (2 == bladeJob.getJobType()) {
                object = SpringUtil.getBean(bladeJob.getJobName());
            }

            if (object != null) {
                clazz = object.getClass();
                Method method = null;
                if (StringUtil.isNotBlank(bladeJob.getMethodParameters())) {
                    method = clazz.getDeclaredMethod(bladeJob.getMethodName(), new Class[]{Object.class});
                    method.invoke(object, bladeJob.getMethodParameters());
                } else {
                    method = clazz.getDeclaredMethod(bladeJob.getMethodName());
                    method.invoke(object);
                }
                flag=false;
            }
            if (false){
                System.out.println("任务执行异常，移除任务");
                JobUtil.delJob(bladeJob);
            }


        } catch (Exception e) {
            System.out.println("任务执行异常，移除任务");
            asyncService.sendAdminMail(bladeJob.getJobName()+"."+bladeJob.getMethodName(), "任务执行异常，已终止任务");
            JobUtil.delJob(bladeJob);
            e.printStackTrace();

        }
    }
}